/**
 * 研发流程状态机 - 状态历史记录管理
 */

const { cloudHelper } = require('../../../config/project_helpers_config');
const { timeHelper } = require('../../../config/project_helpers_config');
const { PROJECT_STATUS_NAMES, ACTIVE_STATE_NAMES } = require('./constants');

/**
 * 状态历史记录管理类
 */
class StateHistoryManager {
  /**
   * 构造函数
   * @param {String} projectId 项目ID
   */
  constructor(projectId) {
    this.projectId = projectId;
    this.history = [];
    this.stateStack = [];
  }
  
  /**
   * 加载状态历史记录
   * @returns {Promise<void>}
   */
  async loadHistory() {
    try {
      const result = await cloudHelper.callCloudData('research/state_history', {
        projectId: this.projectId
      });
      
      if (result && result.history) {
        this.history = result.history;
        this.stateStack = result.stateStack || [];
      }
    } catch (error) {
      console.error('加载状态历史记录失败:', error);
      throw error;
    }
  }
  
  /**
   * 添加状态变更记录
   * @param {Object} fromState 原状态
   * @param {Object} toState 目标状态
   * @param {String} event 触发事件
   * @param {String} operator 操作人
   * @param {String} reason 变更原因
   * @returns {Promise<void>}
   */
  async addHistoryRecord(fromState, toState, event, operator, reason = '') {
    try {
      const record = {
        projectId: this.projectId,
        fromState: this._formatState(fromState),
        toState: this._formatState(toState),
        event,
        operator,
        reason,
        timestamp: timeHelper.getCurrentTimestamp(),
        stateStack: [...this.stateStack]
      };
      
      // 保存到云数据库
      await cloudHelper.callCloudData('research/add_state_history', record);
      
      // 更新本地历史记录
      this.history.push(record);
      
      // 更新状态栈
      this._updateStateStack(toState);
    } catch (error) {
      console.error('添加状态历史记录失败:', error);
      throw error;
    }
  }
  
  /**
   * 获取状态变更历史
   * @returns {Array} 历史记录列表
   */
  getHistory() {
    return this.history;
  }
  
  /**
   * 获取状态栈
   * @returns {Array} 状态栈
   */
  getStateStack() {
    return this.stateStack;
  }
  
  /**
   * 回退到上一个状态
   * @returns {Object|null} 上一个状态，如果没有则返回null
   */
  rollbackState() {
    if (this.stateStack.length <= 1) {
      return null;
    }
    
    // 弹出当前状态
    this.stateStack.pop();
    
    // 返回上一个状态
    return this.stateStack[this.stateStack.length - 1];
  }
  
  /**
   * 格式化状态对象
   * @param {Object} state 状态对象
   * @returns {Object} 格式化后的状态对象
   * @private
   */
  _formatState(state) {
    return {
      level1: state.level1,
      level1Name: PROJECT_STATUS_NAMES[state.level1] || '未知状态',
      level2: state.level2 || '',
      level3: state.level3 || '',
      level4: state.level4 || '',
      level3Name: state.level3 ? (ACTIVE_STATE_NAMES[state.level3] || state.level3) : '',
      timestamp: timeHelper.getCurrentTimestamp()
    };
  }
  
  /**
   * 更新状态栈
   * @param {Object} state 新状态
   * @private
   */
  _updateStateStack(state) {
    // 如果状态栈为空，直接添加
    if (this.stateStack.length === 0) {
      this.stateStack.push(this._formatState(state));
      return;
    }
    
    // 获取当前状态
    const currentState = this.stateStack[this.stateStack.length - 1];
    
    // 如果状态发生变化，添加到栈中
    if (currentState.level1 !== state.level1 ||
        currentState.level2 !== state.level2 ||
        currentState.level3 !== state.level3 ||
        currentState.level4 !== state.level4) {
      this.stateStack.push(this._formatState(state));
    }
  }
}

module.exports = StateHistoryManager; 